//
//  ViewController.m
//  闪电超市
//
//  Created by 李典 on 16/11/3.
//  Copyright © 2016年 李典. All rights reserved.
//

#import "AXFFlashSupermarketController.h"
#import "AXFFoodModel.h"
#import "AXFLeftTableViewCell.h"
#import "AXFRightTableViewCell.h"
#import "AXFDetailsModel.h"
#import "AXFRankView.h"
#import <UIImageView+WebCache.h>
#import "AXFNetworkingTools.h"
#import "AXFHUDView.h"
#import <MJRefresh.h>
#import "AXFShoppingCartController.h"
#import "AXFModelManager.h"
#import "AXFNavView.h"
#import "AXFDetailViewController.h"
static NSString *cellID = @"DianLID";
@interface AXFFlashSupermarketController ()<
UITableViewDelegate,
UITableViewDataSource,
AXFRightTableViewCell,
CAAnimationDelegate,
AXFRankView
>

@property (nonatomic, weak) UITableView *rightTableView;
@property (nonatomic, weak) UITableView *leftTableView;
@property (nonatomic, weak) AXFRankView *rightView;
@property (nonatomic, strong) NSArray <AXFFoodModel *> *foodArray;
@property (nonatomic, strong) NSDictionary *detailArray;
@property (nonatomic, strong) NSMutableArray <AXFDetailsModel *>*modelList;
@property (nonatomic, strong) NSMutableDictionary *dictShopID;
@property (nonatomic, strong) NSMutableArray *arrayModel;
@property (nonatomic, strong) AXFDetailsModel *model;
@property (nonatomic, strong) NSIndexPath *indexP;
@property (nonatomic, weak) MBProgressHUD *hud;
@property (nonatomic, weak) UIView *HUDView;
@property (nonatomic,weak)AXFNavView *navView;
//下拉刷新
@property (nonatomic, weak) MJRefreshGifHeader *headerView;

@property (nonatomic, weak) AXFShoppingCartController *cartCon;
@property (nonatomic, strong) AXFModelManager *modelManager;
@property (nonatomic, strong) NSMutableArray *managerModelList;

@end

@implementation AXFFlashSupermarketController
{
    UITableViewCell *_cell;
    UIButton *_btn;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    AXFModelManager *modelManager = [AXFModelManager shareModelManager];
    self.modelManager = modelManager;
    self.managerModelList = modelManager.managerModelList;
    
    [self.rightTableView reloadData];
    
    self.navigationController.navigationBar.hidden = YES;
    if (self.homeIndexItem == 5) {
        return;
    }
    [_leftTableView reloadData];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    [self pullDownLoadData];
    AXFShoppingCartController *cartCon = [[AXFShoppingCartController alloc]init];
    self.cartCon = cartCon;
    [AXFModelManager shareModelManager];
    self.arrayModel = [[NSMutableArray alloc]init];
    self.dictShopID = [[NSMutableDictionary alloc]init];
}


#pragma mark - 5.实现加号按钮动画效果
// ➕号方法
- (void)addGoodsWithCell:(AXFRightTableViewCell *)rightTableViewCell withAddModel:(AXFDetailsModel *)model andPicturePoint:(CGPoint)picturePoint
{
    
    if (![_modelList containsObject:model]) {
        [_modelList addObject:model];
    }
    
    [self creatAnimateStartPoint:picturePoint WithModel:model];
    
    NSDictionary *userInfo = @{@"model":model};
    [[NSNotificationCenter defaultCenter]   postNotificationName:@"shoppingCart" object:self userInfo:userInfo];
}

// ➖号方法
- (void)minusGoodsWithCell:(AXFRightTableViewCell *)rightTableViewCell withMinusModel:(AXFDetailsModel *)model
{
    NSDictionary *userInfo = @{@"model":model};
    [[NSNotificationCenter defaultCenter]   postNotificationName:@"shoppingCart" object:self userInfo:userInfo];
}
// 创建动画
- (void)creatAnimateStartPoint:(CGPoint)startPoint WithModel:(AXFDetailsModel *)model
{
    UIImageView *currentImage = [[UIImageView alloc]init];
    NSURL *urlStr = [NSURL URLWithString:model.img];
    currentImage.backgroundColor = [UIColor redColor];
    currentImage.bounds = CGRectMake(0, 0, 80, 80);
    //    [currentImage sd_setImageWithURL:urlStr];
    [currentImage sd_setImageWithURL:urlStr completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        currentImage.center = startPoint;
        //    NSLog(@"+++++");
        //获取 当时获取坐标位置的window
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        //添加图片
        [keyWindow addSubview:currentImage];
        //创建一个关键帧动画    才能一次执行多个动画  否则普通动画只能执行一个      position：位置  移动位置
        CAKeyframeAnimation *keyAni = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        //   贝塞尔曲线
        UIBezierPath *path = [UIBezierPath bezierPath];
        // 起点
        [path moveToPoint:startPoint];
        
        // 跳跃位置
        //        CGPoint middlePoint = CGPointMake(startPoint.x, startPoint.y - 44);
        
        // 终点的位置
        CGPoint endPoint = CGPointMake(200, 667 - 44);
        
        //  设置路径
        [path addLineToPoint:endPoint];
        //        [path addCurveToPoint:endPoint controlPoint1:startPoint controlPoint2:middlePoint];
        keyAni.path = path.CGPath;
        //时间
        keyAni.duration = .5;
        [UIView animateWithDuration:.5 animations:^{
            
            currentImage.transform = CGAffineTransformMakeScale(0.2, 0.2);
        }];
        
        //  遵守代理    这个是animation独有的
        keyAni.delegate = self;
        
        //    5.在动画结束之后删除      在动画添加之前 保存到字典中
        [keyAni setValue:currentImage forKey:@"endImage"];
        
        [currentImage.layer addAnimation:keyAni forKey:@"keyAni"];
    }];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    UIImageView *endView = [anim valueForKey:@"endImage"];
    [endView removeFromSuperview];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _leftTableView) {
        [self tableView:tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:self.homeIndexItem inSection:0]];
        
        if (indexPath.row == self.homeIndexItem) {
            [cell setSelected:YES];
            _cell = cell;
        }
    }
    
}
#pragma mark - 4.点击左侧右侧跳转
// 点击左侧右侧跳转到当前位置
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tracking || tableView.dragging || tableView.decelerating) {//自动
        return;
    }
    
    if (tableView == _leftTableView) {
        if (indexPath.row != self.homeIndexItem) {
            _cell.selected = NO;
        }
        self.indexP = indexPath;
        
        NSString *shopID = _foodArray[indexPath.row].shopId;
        NSArray *array = self.detailArray[shopID];
        NSMutableArray *arrayRTM = [[NSMutableArray alloc]init];
        //        NSMutableArray *arrayModel = [[NSMutableArray alloc]init];
        
        if ([self.dictShopID objectForKey:shopID]) {
            self.modelList = [self.dictShopID objectForKey:shopID];
            [self reloadDataRighTable];
            return;
        }
        [array enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            _model = [[AXFDetailsModel alloc]init];
            [_model setValuesForKeysWithDictionary:obj];
            [arrayRTM addObject:_model];
        }];
        [self.dictShopID setObject:arrayRTM.copy forKey:shopID];
        //        [_arrayModel addObject:arrayRTM];
        self.modelList = arrayRTM.copy;
        
        // 遍历数组
        for (int i = 0; i < self.modelList.count; i++) {
            
            AXFDetailsModel *m = self.modelList[i];

                for (int j = 0; j < [AXFModelManager shareModelManager].managerModelList.count; j++) {
                    AXFDetailsModel *newj = [AXFModelManager shareModelManager].managerModelList[j];
        

                    if ([m.name isEqualToString:newj.name]) {
                        m.shopCount = newj.shopCount;
                    }
            }
            
        }
        
        [self reloadDataRighTable];
        
    }
    
    if (tableView == _rightTableView) {
        AXFDetailsModel *detailsModel = self.modelList[indexPath.row];
        NSLog(@"%@",detailsModel.product_id);
        
        AXFDetailViewController *detailViewController = [[AXFDetailViewController alloc] init];
        
        detailViewController.detailsModel = detailsModel;
        
        [self.navigationController pushViewController:detailViewController animated:YES];
    }
}


#pragma mark - 排序功能代理方法
- (void)againSequence:(UIButton *)btn
{
    switch (btn.tag) {
        case kAllRankBtn:
            //            NSLog(@"zonghe");
            self.modelList = [self.modelList sortedArrayUsingComparator:^NSComparisonResult(AXFDetailsModel *obj1, AXFDetailsModel *obj2) {
                return [obj1.name compare:obj2.name];
            }].mutableCopy;
            [self reloadDataRighTable];
            break;
        case kPriceUpRankBtn:
            //            NSLog(@"jiage");
            self.modelList = [self.modelList sortedArrayUsingComparator:^NSComparisonResult(AXFDetailsModel *obj1, AXFDetailsModel *obj2) {
                return [@(obj1.partner_price).description compare:@(obj2.partner_price).description];
            }].mutableCopy;
            [self reloadDataRighTable];
            break;
        case kPriceDownRankBtn:
            self.modelList = [self.modelList sortedArrayUsingComparator:^NSComparisonResult(AXFDetailsModel *obj1, AXFDetailsModel *obj2) {
                return [@(obj2.partner_price).description compare:@(obj1.partner_price).description];
            }].mutableCopy;
            [self reloadDataRighTable];
            break;
        case kSalesRankBtn:
            //            NSLog(@"xiaoliang");
            self.modelList = [self.modelList sortedArrayUsingComparator:^NSComparisonResult(AXFDetailsModel *obj1, AXFDetailsModel *obj2) {
                return [obj1.number.description compare:obj2.number.description];
            }].mutableCopy;
            [self reloadDataRighTable];
            break;
        default:
            break;
    }
}

- (void)reloadDataRighTable
{
    [self.rightTableView reloadData];
    // 滚动到顶部
    [self.rightTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:_indexP.section] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
#pragma mark - 3.tableView数据源方法


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.leftTableView) {
        return _foodArray.count;
    }
    return _modelList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    if (tableView == _leftTableView) {
        cell.textLabel.text = _foodArray[indexPath.row].name;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }else if (!(self.model.shopCount == 0)) {
        ((AXFRightTableViewCell *)cell).model = self.managerModelList[indexPath.row];
    }else{
        ((AXFRightTableViewCell *)cell).model = _modelList[indexPath.row];
        ((AXFRightTableViewCell *)cell).delegate = self;
        //        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return cell;
}

// MARK: 下拉刷新
- (void)pullDownLoadData
{
    NSArray *GIFImageArray = [NSArray arrayWithObjects:
                              [UIImage imageNamed:@"v2_pullRefresh1"],
                              [UIImage imageNamed:@"v2_pullRefresh2"],
                              nil];
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    self.headerView = header;
    
    [header setImages:GIFImageArray forState:MJRefreshStatePulling];
    
    
    header.lastUpdatedTimeLabel.hidden = YES;
    //    header.stateLabel.hidden = YES;
    [header setTitle:@"下拉刷新..." forState:MJRefreshStateIdle];
    [header setTitle:@"松开我就刷新啦.." forState:MJRefreshStatePulling];
    self.rightTableView.mj_header = header;
    
    
}
- (void)loadNewData
{
    [self.rightTableView reloadData];
    [self.headerView endRefreshing];
}

#pragma mark - 2.创建UI界面
- (void)setupUI
{
    //  加载界面
    UIView *HUDView = [AXFHUDView creatHudViewWithHUDLoadingTitle:@"滴滴滴开车啦..." titleFont:12 HUDMode:MBProgressHUDModeIndeterminate];
    self.HUDView = HUDView;
    
    self.title = @"闪购超市";
    // MARK:创建视图
    //      1.左面的tableView
    UITableView *leftTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view insertSubview:leftTableView belowSubview:HUDView];
    self.leftTableView.showsVerticalScrollIndicator = NO;
    self.leftTableView.showsHorizontalScrollIndicator = NO;
    
    //      2.右面的tableView
    UITableView *rightTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view insertSubview:rightTableView belowSubview:HUDView];
    rightTableView.rowHeight = UITableViewAutomaticDimension;
    rightTableView.estimatedRowHeight = 120;
    
    //      3.右侧View
    AXFRankView *rightView = [[AXFRankView alloc]init];
    [self.view insertSubview:rightView belowSubview:HUDView];
    
    //      4. 上方假Navgation
    AXFNavView *navView = [[AXFNavView alloc] init];
    self.navView = navView;
    [navView setContainerViewAlpha:1];
    [self.view addSubview:navView];
    [self.view insertSubview:HUDView belowSubview:navView];
    
    //    MARK: 设置数据源代理
    rightView.delegate = self;
    rightTableView.delegate = self;
    rightTableView.dataSource = self;
    leftTableView.delegate = self;
    leftTableView.dataSource = self;
    self.rightTableView = rightTableView;
    self.leftTableView = leftTableView;
    self.rightView = rightView;
    
    [rightTableView registerClass:[AXFRightTableViewCell class] forCellReuseIdentifier:cellID];
    [leftTableView registerClass:[AXFLeftTableViewCell class] forCellReuseIdentifier:cellID];
    
    //    MARK: 视图布局
    //顶部Navgation
    [navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.equalTo(@64);
    }];
    
    
    [leftTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.equalTo(self.view);
        make.top.equalTo(navView.mas_bottom);
        make.width.mas_equalTo(80);
    }];
    [rightView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftTableView.mas_right);
        make.top.equalTo(self.view).offset(64);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(42);
    }];
    [rightTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(self.view);
        make.left.equalTo(leftTableView.mas_right);
        make.top.equalTo(rightView.mas_bottom);
    }];
    // 右侧tableView的 底部视图
    UIImageView *footView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"v2_common_footer"]];
    footView.contentMode = UIViewContentModeCenter;
    rightTableView.tableFooterView = footView;
}

#pragma mark - 1.数据加载
- (void)loadData
{
    NSString *urlStr = @"https://raw.githubusercontent.com/Ma7777777/test/master/FlashSupermarket.json";
    
//    NSString *urlStr = [[NSBundle mainBundle]pathForResource:@"Home.json" ofType:nil];
//    
//   NSURL *url = [NSURL fileURLWithPath:urlStr];
    
    [[AXFNetworkingTools sharedManager] getNewTableCellWithUrl:urlStr completeLeftCell:^(NSArray *responseOBJ, NSError *error) {
        
        NSArray <AXFFoodModel *> *arrayLTM = [NSArray yy_modelArrayWithClass:[AXFFoodModel class] json:responseOBJ];
        self.foodArray = arrayLTM.copy;
        [_leftTableView reloadData];
        
        //   加载数据前的界面动画
        self.hud.hidden = [MBProgressHUD hideHUDForView:self.view animated:NO];
        [self.HUDView removeFromSuperview];
        
    } completeRightCell:^(NSDictionary *responseOBJ, NSError *error) {
        
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        [responseOBJ enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            [dict setObject:obj forKey:key];
        }];
        
        
        self.detailArray = dict.copy;
        [_rightTableView reloadData];
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
